package ai4games_tests.tests;

import game2dai.World;
import game2dai.entities.Vehicle;
import game2dai.entityshapes.ps.ArrowPic;
import game2dai.graph.GraphNode;
import game2dai.maths.Vector2D;
import game2dai.utils.StopWatch;

import java.util.LinkedList;

import processing.core.PApplet;

public class PathFollow_001 extends PApplet {
	
	World world;
	Vehicle dart;
	StopWatch sw;
	// List used to display path being followed
	LinkedList<Vector2D> route = new LinkedList<Vector2D>();

	public void setup(){
		size(640,400);
		world = new World(width, height);
		sw = new StopWatch();
		
		dart = new Vehicle(
				new Vector2D(320, 170), // position
				10,                     // collision radius
				new Vector2D(0, 0),     // velocity
				50,                     // maximum speed
				new Vector2D(1, 0),     // heading
				1,                      // mass
				4,                      // turning rate
				200                     // max force
		); 
		ArrowPic view = new ArrowPic(this);		
		dart.renderer(view);
		// Set path way-point and destinations distances then 
		// switch path following on.
		dart.AP().pathFactors(8, 1).pathOn();
		// The world will manage this vehicle
		world.add(dart);
		// Add the starting position
		route.add(new Vector2D(dart.pos()));

		sw.reset();
	}
	
	public void draw(){
		double deltaTime = sw.getElapsedTime();
		world.update(deltaTime);
		// Stop the vehicle at the end of the path
		if(dart.AP().pathRouteLength() == 0)
			dart.velocity(0,0);
		// Ready to draw
		background(60,128,60);
		// Draw play area
		fill(100,200,100);
		noStroke();
		rect(20, 40, width-40, height-60);
		// Display instructions
		fill(255);
		text("Click inside the play area to extend the path", 20, 30);
		drawRoute();
		world.draw();
	}

	public void mouseClicked(){
		if(mouseX > 20 && mouseX < width - 20 && mouseY > 40 && mouseY <height - 20){
			Vector2D wp = new Vector2D(mouseX, mouseY);
			route.add(wp);
			dart.AP().pathAddToRoute(wp);
		}
	}

	// Display the path being followed.
	public void drawRoute(){
		Vector2D p0, p1;
		// Remove paths that have been travelled
		while(route.size() > dart.AP().pathRouteLength() + 1)
			route.removeFirst();
		// Draw the path to follow (if any)
		if(route.size() > 1){
			stroke(0,64,0);
			strokeWeight(1);
			p0 = route.get(0);
			for(int i = 1; i < route.size(); i++){
				p1 = route.get(i);
				line((float)p0.x, (float)p0.y, (float)p1.x, (float)p1.y);
				p0 = p1;
			}
		}
	}
	
	public void drawRoute2(){
		LinkedList<GraphNode> route = dart.AP().pathRoute();
		GraphNode p0, p1;
		
		// Draw the path to follow (if any)
		if(route.size() > 1){
			stroke(0,64,0);
			strokeWeight(1);
			p0 = route.get(0);
			for(int i = 1; i < route.size(); i++){
				p1 = route.get(i);
				line(p0.xf(), p0.yf(), p1.xf(), p1.yf());
				p0 = p1;
			}
		}		
	}
	
}
